﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Crossroad.Utils.Extensions;
using Crossroad.Core.Configs;

namespace Crossroad.Core.Helper
{
    /// <summary>
    /// 依赖注入模块注册
    /// </summary>
    public class AutofacModuleRegister : Autofac.Module
    {
        /// <summary>
        /// 重写Autofac管道Load方法，在这里注册注入
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            if (AppConfig.AutofacModules.IsNullOfEmpty())
                return;

            //注册Service中的对象,Service中的类要以Service结尾，否则注册失败
            foreach (var module in AppConfig.AutofacModules.Split(','))
            {
                builder.RegisterAssemblyTypes(GetAssemblyByName(module))
                    .Where(a => a.Name.EndsWith("Service") || a.Name.EndsWith("Job"))
                    .AsImplementedInterfaces()
                    .InstancePerLifetimeScope();
            }

            builder.RegisterBuildCallback(container => new AutofacOption(container));
        }

        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名称</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(string AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }


    }
}
